import { useReactive } from "ahooks";
import { useModel } from "umi";
import { useEffect } from "react";
import compress from "gql-compress";

const useAllStores = (oiType) => {
    const { graphqlFetch } = useModel("global");

    const state = useReactive({
        loading: false,
        stores: [],
    });

    // 加载所有部门信息, 用树的数据格式
    const loadAllStores = async (oiType) => {
        state.loading = true;
        let res = await graphqlFetch({
            query,
            variables: {
                oiType,
            },
        });
        let stores =
            res?.a?.nodes.map((item) => {
                return {
                    ...item,
                    id: item.oiUuid,
                    type: "store",
                };
            }) || [];
        state.stores = stores;
        state.loading = false;
        return stores;
    };

    useEffect(() => {
        oiType && loadAllStores(oiType);
    }, [oiType]);

    return { ...state, loadAllStores };
};

const query = compress(`query MyQuery($oiType: String!) {
    a: allOrganizationInstitutions(condition: {oiType: $oiType, oiRoot: null}, orderBy: PY_NAME_ASC) {
        nodes {
            asInfo
            crInfo
            maInfo
            mpInfo
            oiCity
            oiComm
            oiDesc
            oiDist
            oiEsta
            oiLeve
            oiName
            oiPaid
            oiPhon
            oiPrin
            oiRoot
            oiStat
            oiStre
            oiType
            oiUuid
            oiZoja
            otInfo
            ptInfo
            pyName
            upInfo
            oiAddr
            ptInfo
        }
    }
}`);

export default useAllStores;
